<?php
$self_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
$api = isset($_GET['api']) ? $_GET['api'] : 'login/ads';
$authCode = isset($_GET['authCode']) ? $_GET['authCode'] : '';

/**
 * 例：
 * 'URL'=>[
 *      name=>'接口中文名称',
 *      method=>'表单提交方式',
 *      keys=>[
 *          '字段名称'=>[
 *              'must' => 是否必填(true/false),
 *              'name' => '字段中文名称',
 *              'type' => '字段类型(string/date/int/boolean/array 或者使用or传多种类型)',
 *              'default' => '字段默认值',
 *          ]
 *      ]
 * ]
 */
$keys_array = [
    'login/ads' => [
        'name' => '展示登录的广告图片',
        'method' => 'get',
        'keys' => [

        ],
    ],
    'login/post' => [
        'name' => '登录模块',
        'method' => 'post',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'password' => [
                'must' => true,
                'name' => '密码',
                'type' => 'string',
            ],
            'loginTime' => [
                'must' => true,
                'name' => '密码',
                'type' => 'int',
                'default' => time(),
            ],
            'ip' => [
                'must' => true,
                'name' => '登录IP',
                'type' => 'string',
                'default' => '127.0.0.1',
            ],
        ],
    ],
    'member/order/order_list' => [
        'name' => '商品订单列表',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'search' => [
                'must' => false,
                'name' => '订单状态',
                'type' => 'int',
            ],
            'order_status' => [
                'must' => false,
                'name' => '订单时间',
                'type' => 'int',
            ],
            'order_time' => [
                'must' => false,
                'name' => '关键字',
                'type' => 'string',
                'default' => "",
            ],
            'page' => [
                'must' => false,
                'name' => '第几页',
                'type' => 'int',
                'default' => 1,
            ],
        ],
    ],
    'member/order/combine_pay' => [
        'name' => '合并付款',
        'method' => 'post',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号（组合）',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/combine_daifu' => [
        'name' => '合并代付',
        'method' => 'post',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号（组合）',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/batch_receive' => [
        'name' => '批量确认收货',
        'method' => 'post',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号（组合）',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/now_pay' => [
        'name' => '立即支付',
        'method' => 'post',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/daifu' => [
        'name' => '找人代付',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/cancel_order' => [
        'name' => '取消订单',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
            'reason' => [
                'must' => true,
                'name' => '理由',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/del_order' => [
        'name' => '删除订单',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/refund_pay_goods' => [
        'name' => '退款退货',
        'method' => 'post',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
            'type' => [
                'must' => true,
                'name' => '1退款 2退货',
                'type' => 'int',
                'default' => 1
            ],
            'reason' => [
                'must' => true,
                'name' => '理由',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/wuliu' => [
        'name' => '物流追踪',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/notice_shipping' => [
        'name' => '提醒卖家发货',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/confirm_receive' => [
        'name' => '确认收货',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/recycle_order_list' => [
        'name' => '商品订单回收站列表',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'page' => [
                'must' => true,
                'name' => '第几页',
                'type' => 'int',
                'default' => 1,
            ],
        ],
    ],
    'member/order/restore_order' => [
        'name' => '恢复订单',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/del_order_forever' => [
        'name' => '永久删除订单',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
    'member/order/receive_confirm_pay' => [
        'name' => '收货后确认付款',
        'method' => 'get',
        'keys' => [
            'username' => [
                'must' => true,
                'name' => '用户名',
                'type' => 'string',
            ],
            'order_id' => [
                'must' => true,
                'name' => '订单编号',
                'type' => 'string',
            ],
        ],
    ],
];

$api_info = isset($keys_array[$api]) ? $keys_array[$api] : '';


?>

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title><?php echo $api_info['name']; ?></title>
    <link rel="stylesheet" href="./public/style/bootstrap.min.css"/>
    <link rel="stylesheet" href="./public/style/loaders.css"/>
    <style type="text/css">
        pre {
            outline: 1px solid #ccc;
            padding: 5px;
            margin: 5px;
        }

        .string {
            color: green;
        }

        .number {
            color: darkorange;
        }

        .boolean {
            color: blue;
        }

        .null {
            color: magenta;
        }

        .key {
            color: red;
        }

        td {
            vertical-align: middle !important;
        }

        #loading-div {
            position: fixed;
            top: 0;
            left: 0;
            height: 100%;
            width: 100%;
            background-color: transparent;
            display: none;
        }

        #loading-div .line-scale {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            height: 50px;
            width: 50px;
        }

        #loading-div .line-scale > div {
            background: orange;
        }

        .nav-box {
            position: fixed;
            left: 0;
            top: 70px;
            bottom: 0;
            padding: 20px 15px;
            overflow-y: auto;
            border-right: 1px solid #f0f0f0;
        }

        .nav-box ul {
            /*margin-top: 70px;*/
        }
    </style>
</head>
<body>

<div class="container-fluid">
    <h1>API接口测试工具</h1>
    <div class="nav-box col-md-2 col-sm-2 col-xs-2">
        <ul class="nav nav-pills nav-stacked" role="tablist">
            <?php foreach ($keys_array as $k => $v) { ?>
                <li class="<?php if ($k == $api) {
                    echo 'active';
                } ?>"><a
                            href="?api=<?php echo $k; ?>&authCode=<?php echo $authCode; ?>"><?php echo $v['name']; ?></a>
                </li>
            <?php } ?>
        </ul>
    </div>
    <div class="row">
        <div class="col-md-10 col-sm-10 col-xs-10 col-md-offset-2 col-sm-offset-2 col-xs-offset-2">
            <form>
                <table id="old_data" class="table table-bordered text-center">
                    <thead style="display:none">
                    <tr>
                        <td>
                            API
                        </td>
                        <td colspan="3">
                            <input type="text" class="form-control" placeholder="http://uthing.cn" name="url"
                                   value="apitest.php" readonly>
                        </td>
                    </tr>
                    </thead>
                    <thead>
                    <tr>
                        <td style="width: 100px;">
                            API_URL
                        </td>
                        <td colspan="3">
                            <input type="text" class="form-control" placeholder="http://pc.oomall.com" name="api_url"
                                   value="<?php echo !empty($api) ? $api : ''; ?>" readonly>
                        </td>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    if (!empty($api_info)) {
                        echo "<h3>" . $api_info['name'] . "</h3>";
                        $m = 1;
                        foreach ($api_info['keys'] as $key => $value) {
                            ?>
                            <tr>
                                <td>
                                    <?php echo $value['name']; ?><br><span
                                            style="color:red"><?php echo isset($value['type']) ? $value['type'] : 'string'; ?></span>
                                    <input type="hidden" class="k_v_<?php echo $m; ?>" name="" value="">
                                </td>
                                <td><input type="text" data-class="k_v_<?php echo $m; ?>" class="key_input form-control"
                                           placeholder="KEY"
                                           value="<?php echo $key; ?>" <?php if ($value['must'] == true) {
                                        echo "readonly";
                                    } ?>></td>
                                <td><input type="text" data-class="k_v_<?php echo $m; ?>" class="val_input form-control"
                                           placeholder="VALUE" <?php if ($value['must'] == true) {
                                        echo "data-require='true' data-message='{$key}必填'";
                                    } ?> value="<?php echo isset($value['default']) ? $value['default'] : ''; ?>"></td>
                                <td style="width:60px;"><?php if ($value['must'] == false) { ?>
                                        <button type="button" class="btn btn-default btn-remove">-
                                        </button><?php } else { ?><span style="color:red">必填</span><?php } ?></td>
                            </tr>
                            <?php
                            $m++;
                        }
                    } ?>
                    </tbody>
                    <tbody>
                    <tr>
                        <td>
                            参数
                            <input type="hidden" class="k_v_0" name="" value="">
                        </td>
                        <td><input type="text" data-class="k_v_0" class="key_input form-control" placeholder="KEY"
                                   value=""></td>
                        <td><input type="text" data-class="k_v_0" class="val_input form-control" placeholder="VALUE">
                        </td>
                        <td style="width:60px;">
                            <button type="button" class="btn btn-default btn-remove">-</button>
                        </td>
                    </tr>
                    </tbody>
                    <tfoot>
                    <tr>
                        <td></td>
                        <td colspan="3">
                            <button type="button" class="btn btn-default btn-add">添加参数</button>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="4" class="form-inline">
                            <div class="form-group">
                                提交方式
                                <select name="method" class="form-control">
                                    <option value="post" <?php echo isset($api_info['method']) && $api_info['method'] == "post" ? 'selected' : ''; ?>>
                                        POST
                                    </option>
                                    <option value="get" <?php echo isset($api_info['method']) && $api_info['method'] == "get" ? 'selected' : ''; ?>>
                                        GET
                                    </option>
                                </select>
                                返回格式
                                <select name="type" class="form-control">
                                    <option value="json" selected>json</option>
                                    <option value="array">array</option>
                                </select>
                            </div>
                            <a href="javascript:;" class="btn btn-primary btn-submit">提交</a>
                        </td>
                    </tr>
                    </tfoot>
                </table>
            </form>

            <div class="panel panel-default" id="new-data">
                <div class="panel-heading">结果</div>
                <div class="panel-body">
                    此处要显示查出来的信息
                </div>
            </div>
        </div>
    </div>

    <script src="//cdn.bootcss.com/jquery/1.10.0/jquery.js"></script>
    <script type="text/javascript">
        (function ($) {

            $.fn.extend({
                'validate': function () {
                    var $require_list = this.find('.u_validate, input[data-require=true], select[data-require=true]'),
                        is_pass = true,
                        message = false,
                        regexps = {
                            email: "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*",
                            phone: "^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|17[0|1|2|3|5|6|7|8|9])\\d{8}$",
                            number: "^[0-9]+$"
                        },
                        $this, val, regexp, regexpStr, dataRegexp, dataRequire;

                    $require_list.each(function () {

                        $this = $(this);

                        val = $this.val() === null ? '' : $this.val();

                        if (is_pass) {

                            dataRegexp = $this.attr('data-regexp');

                            dataRequire = $this.attr('data-require');

                            if (dataRegexp) {

                                regexpStr = regexps[dataRegexp];

                                if (regexpStr == undefined) {
                                    regexpStr = dataRegexp;
                                }

                                regexp = new RegExp(regexpStr);

                                if (dataRequire == 'false' && val == '') {

                                } else if (!regexp.test(val)) {
                                    is_pass = false;
                                    message = $(this).data('message');
                                }

                            } else if (message === false && (/^\s+|\*$/.test(val + '') || (val + '').length === 0)) {
                                is_pass = false;
                                message = $(this).data('message');
                            }
                        }
                    });

                    if (!is_pass) {
                        alert(message);
                    }

                    return is_pass;
                }
            });

        })(jQuery);

        //参数处理
        var ParamsHandler = function () {
            var $table = $('#old_data tbody:last');
            var trTemplate = '<tr>' + $table.find("tr").eq(0).html() + '</tr>';

            function add(index) {
                $table.append(trTemplate.replace(/(k_v_)0/g, '$1' + ( index )).replace(/([key|val])\[0\]/g, '$1[' + ( index ) + ']'));
            }

            return {
                init: function () {
                    var index = $('#old_data tbody').find('tr').length;
                    $('.btn-add').click(function () {
                        console.log(index);
                        index++;
                        add(index);
                    });
                    $(document)
                        .on('click', '.btn-remove', function () {
                            if ($table.find('tr').length === 1) return false;
                            $(this).closest('tr').remove();
                        });
                }
            }
        }();
        //ajax结果处理
        var AjaxResultHandler = function () {
            function syntaxHighlight(json) {
                if (typeof json != 'string') {
                    json = JSON.stringify(json, undefined, 2);
                }
                json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
                    var cls = 'number';
                    if (/^"/.test(match)) {
                        if (/:$/.test(match)) {
                            cls = 'key';
                        } else {
                            cls = 'string';
                        }
                    } else if (/true|false/.test(match)) {
                        cls = 'boolean';
                    } else if (/null/.test(match)) {
                        cls = 'null';
                    }
                    return '<span class="' + cls + '">' + match + '</span>';
                });
            }

            function showResultWithFormat(type, result) {
                if (type === 'json') {
                    $("#new-data .panel-body").html('<pre>' + syntaxHighlight(JSON.parse(result)) + '</pre>');
                } else {
                    $("#new-data .panel-body").html('<pre>' + result + '</pre>');
                }
            }

            return {
                highlight: syntaxHighlight,
                show: showResultWithFormat
            }
        }();

        var Loading = function () {

            var loadingDivID = 'loading-div',
                loadingDiv = null;

            function createElement() {
                var loadingDiv = $('<div id="' + loadingDivID + '"><div class="line-scale"><div></div><div></div><div></div><div></div><div></div></div></div>');
                $('body').append(loadingDiv);
                return loadingDiv;
            }

            function getLoadingDiv() {
                loadingDiv = $('#' + loadingDivID);
                return loadingDiv.length > 0 ? loadingDiv : createElement();
            }

            return {
                start: function () {
                    loadingDiv = getLoadingDiv();
                    loadingDiv.fadeIn();
                },
                stop: function () {
                    loadingDiv.fadeOut();
                }
            }
        }();

        var PhpDebugBar = {};

        $(document).ready(function () {
            ParamsHandler.init();
            $(document)
                .on('click', '.btn-submit', function () {

                    if (($('input[name=url]').val() + '').length === 0) return false;

                    $('input.key_input, input.val_input').each(function () {

                        var targetClass = $(this).data('class');

                        if ($(this).hasClass('key_input')) {
                            $('.' + targetClass).attr('name', $(this).val());
                        } else {
                            $('.' + targetClass).attr('value', $(this).val());
                        }

                    });

                    $('form').attr('action', $('input[name=url]').val());
                    $('form').attr('method', $('select[name=method]').val());
                    $('form').attr('type', $('select[name=type]').val());

                    if (!$('form').validate()) return false;

                    Loading.start();
                    try {


                        $.ajax({
                            type: 'post',
                            contentType: 'application/x-www-form-urlencoded',
                            data: $('form').serialize(),
                            url: 'apitest.php',
                            complete: function () {
                                Loading.stop();
                            },
                            success: function (info) {
                                if (info.indexOf('{"code"') > -1) {
                                    AjaxResultHandler.show('json', info);
                                } else {
                                    AjaxResultHandler.show('string', info);
                                }
                            }
                        });
                    } catch (ex) {
                    } finally {
                        Loading.stop();
                    }
                });
        });

    </script>
</div>

</body>
</html>
